package com.briup.corejava.day21;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 客户端的功能实现
 * 1、获取输入
 * 2、不断写入，遇到quit的时候退出
 */
public class TcpClientPlus {
    public static void main(String[] args) {
        // 获取输入
        Scanner sc = new Scanner(System.in);
        // socket
        Socket socket = null;
        // 准备流，发送字符串和接受字符串
        BufferedReader br = null;
        PrintWriter pw = null;
        // 创建
        try {
            socket = new Socket("127.0.0.1", 8888);
            br = new BufferedReader(
                    new InputStreamReader(
                            socket.getInputStream()));
            pw = new PrintWriter(socket.getOutputStream());
            while (true) {
                System.out.print("请输入您的数据：");
                String s = sc.nextLine();
                pw.println(s);
                // pw在用的时候一定要主要写刷新
                pw.flush();
                System.out.println("客户端发送的数据："+s);
                // 遇到quit字符串的时候就结束
                if("quit".equals(s)) break;
                // 接收信息
                String s1 = br.readLine();
                System.out.println("服务器返回的消息："+s1);
            }
        }catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
